using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;

namespace Log2SQL
{
    public class W3CLogImport : LogImport
    {
        private bool _dateFieldExists = false;
        private string _headerDate = "";
        private int _fieldsCount;

        public W3CLogImport() : base()
        {
        }

        protected override void ProcessLine(string line)
        {
            base.ProcessLine(line);
            if (line.IndexOf("#Date: ") > -1)
            {
                _headerDate = line.Substring(7, 10);
                return;
            }

            string[] fields;

            if (line.IndexOf("#Fields: ") > -1)
            {
                //create table (if it is not created allready!!!)
                if (!_isTableCreated)
                {
                    line = line.Substring(9); //remove the "#Fields: " text
                    _dateFieldExists = (line.IndexOf("date ") > -1);
                    if (!_dateFieldExists) //if there's no "date" field - lets add it from the header
                        line = "date " + line;

                    fields = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                    _fieldsCount = fields.Length;
                    SQLCreateTable(_tableNameToWriteTo, fields);
                    _isTableCreated = true;
                }
                return;
            }

            if (_isTableCreated) //if the table has been already created
            {
                //insert individual string (if its not a comment)
                if (line.Substring(0, 1) != "#")
                {
                    if (!_dateFieldExists)
                        line = _headerDate + " " + line;

                    fields = line.Split(new string[] { " " }, StringSplitOptions.None);
                    if (fields.Length == _fieldsCount) //sometimes IIS writes tons of NULLCHARS to the end of the file
                        SQLInsertValues(_tableNameToWriteTo, fields);
                }
            }
        }
    }
}
